package com.tang.base;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.INameConvert;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableField;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;

import java.util.HashSet;
import java.util.Set;

public class CodeGenerator {

    public static void main(String[] args) {
        DataSource dataSource = getDataSource();

        genModuleCode(dataSource, "drawing-base", "system", "sys_");
    }

    private static void genModuleCode(DataSource dataSource, String projectName, String module, String talePrefix) {
        FastAutoGenerator.create(dataSource.getUrl(), dataSource.getUsername(), dataSource.getPassword())
                .globalConfig(builder -> {
                    builder.author("tangzy").outputDir(getDir(projectName)).disableOpenDir();
                }).packageConfig((stringStringFunction, builder) -> {
                    builder.parent("com.tang").moduleName(module);
                }).strategyConfig(builder -> {

                    builder.entityBuilder()
                            .enableLombok()
                            .nameConvert(new MyNameConvert(builder.build()))
                            .enableFileOverride()
                            .enableTableFieldAnnotation();
                    builder.controllerBuilder();
                    builder.addTablePrefix(talePrefix); // 设置过滤表前缀
                }).templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板，默认的是Velocity引擎模板
                .execute();
    }

    private static String getDir(String path) {
        return System.getProperty("user.dir") + "/" + path + "/src/main/java/";
    }

    public static DataSource getDataSource() {
        return DataSource.builder()
                .url("jdbc:mysql://localhost:3309/drawing?characterEncoding=UTF-8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8")
                .username("root")
                .password("root")
                .build();
    }

    @Getter
    @Setter
    @Builder
    static class DataSource {
        private String url;
        private String username;
        private String password;
    }

    static class MyNameConvert extends INameConvert.DefaultNameConvert {
        private final StrategyConfig strategyConfig;

        public MyNameConvert(StrategyConfig strategyConfig) {
            super(strategyConfig);
            this.strategyConfig = strategyConfig;
        }

        @Override
        public String entityNameConvert(TableInfo tableInfo) {
            return NamingStrategy.capitalFirst(this.processName(tableInfo.getName(), this.strategyConfig.entity().getNaming(), new HashSet<>(), this.strategyConfig.getTableSuffix()));
        }

        private String processName(String name, NamingStrategy strategy, Set<String> prefix, Set<String> suffix) {
            String propertyName = name;
            if (!prefix.isEmpty()) {
                propertyName = NamingStrategy.removePrefix(name, prefix);
            }

            if (!suffix.isEmpty()) {
                propertyName = NamingStrategy.removeSuffix(propertyName, suffix);
            }

            if (StringUtils.isBlank(propertyName)) {
                throw new RuntimeException(String.format("%s 的名称转换结果为空，请检查是否配置问题", name));
            } else {
                return NamingStrategy.underline_to_camel.equals(strategy) ? NamingStrategy.underlineToCamel(propertyName) : propertyName;
            }
        }
    }
}
